package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket;

    public TcpEchoClient(String serverIP, int port) throws IOException {
        //与服务器建立连接
        socket = new Socket(serverIP,port);
    }

    public void start() {
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            //对输入流和输出流进行进一步的封装
            Scanner scanner = new Scanner(System.in);
            Scanner scanner2 = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while(true) {
                //发送多个请求和接收多个响应
                if(!scanner.hasNext()) {
                    break;
                }
                //发送请求
                String request = scanner.next();
                writer.println(request);
                writer.flush();
                //接收响应
                String response = scanner2.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
